import { Injectable } from '@angular/core';
import { CanActivateChild, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { switchMap, catchError, tap, filter, take } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { Store } from '@ngrx/store';

import { UserState, LoadUserInfo } from '../../store';
import * as fromUser from '../../store/selectors/user.selector';
import { UserToken } from '../modes';

@Injectable()
export class UserAuthGuard implements CanActivateChild {

  constructor(
    private store: Store<UserState>,
    private router: Router
  ) {}

  canActivateChild(): Observable<boolean> {
    return this.store.select(fromUser.getUserToken).pipe(
      switchMap((userToken: UserToken) => {
        if(userToken) {
          return this.checkUserInfoStore(userToken).pipe(
            switchMap(() => of(true)),
            catchError(() => of(false))
          );
        } else {
          this.router.navigate(['/login']);
          return of(false);
        }
      })
    );
  }

  

  checkUserInfoStore(userToken: UserToken): Observable<boolean> {
    return this.store.select(fromUser.getUserLoaded).pipe(
      tap((loaded: boolean) => {
        if(!loaded) {
          this.store.dispatch(new LoadUserInfo(userToken));
        }
      }),
      filter((loaded: boolean) => loaded),
      take(1)
    );
  }

}
